﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Model.Core.DataBase.EntityFramework
{
    /// <summary>
    /// DateTime类型转换，解决默认DateTime2与DateTime转换的问题
    /// </summary>
    [AttributeUsage(AttributeTargets.Property)]
    public class DateTimeKindAttribute : Attribute
    {
        private readonly DateTimeKind _kind;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="kind"></param>
        public DateTimeKindAttribute(DateTimeKind kind)
        {
            _kind = kind;
        }

        /// <summary>
        /// DateTime类型
        /// </summary>
        public DateTimeKind Kind
        {
            get { return _kind; }
        }

        /// <summary>
        /// 修正实体
        /// </summary>
        /// <param name="entity"></param>
        public static void Apply(object entity)
        {
            if (entity == null)
                return;

            var properties = entity.GetType().GetProperties()
                .Where(x => x.PropertyType == typeof(DateTime) || x.PropertyType == typeof(DateTime?));

            foreach (var property in properties)
            {
                var attr = property.GetCustomAttributes(typeof(DateTimeKindAttribute), true)[0];
                if (attr == null)
                    continue;

                var dt = property.PropertyType == typeof(DateTime?)
                    ? (DateTime?)property.GetValue(entity, null)
                    : (DateTime)property.GetValue(entity, null);

                if (dt == null)
                    continue;

                //property.SetValue(entity, DateTime.SpecifyKind(dt.Value, attr.Kind));
            }
        }
    }
}
